#include "connect_info.h"
#include "decode_unit.h"
#include "client_unit.h"
#include "helper_unit.h"
#include "http_decoder.h"
#include "memcheck.h"

USING_HTTP_SVR_NS

extern map<int,FdInfo>  *g_pFdInfoMap;
extern string           *g_pVersion;
extern CDecodeUnitSet	*g_pDecodeUnitSet;

__BEGIN_DECLS

int SendToClient(int fd , const char* buf , int len)
{
    if( buf == NULL )
        return -1;

    if( g_pFdInfoMap->find(fd) == g_pFdInfoMap->end() )
    {
        return -1;
    }

    FdInfo &fdInfo = (*g_pFdInfoMap)[fd];
    CHelperUnit* pHelperUnit = fdInfo.pHelperUnit;

    if( pHelperUnit == NULL )
    {
        return -2;
    }

    return pHelperUnit->responseCmd(buf , len);
}


int SendToServer(int fd , const char* buf , int len)
{
    if( buf == NULL )
        return -1;
    
    if( g_pFdInfoMap->find(fd) == g_pFdInfoMap->end() )
    {
        return -1;
    }

    FdInfo &fdInfo = (*g_pFdInfoMap)[fd];
    THttpStateInfo* pHttpInfo = fdInfo.pHttpInfo;
    CHelperUnit* pHelperUnit = fdInfo.pHelperUnit;
    if( pHttpInfo==NULL || pHelperUnit==NULL )
    {
        return -2;
    }

    char* tmpbuf = pHttpInfo->get_recvbuf (len + 1);
    if( tmpbuf == NULL )
    {
        return -3;
    }

    memcpy(pHttpInfo->_allsendbuf , buf , len);
    pHttpInfo->_allsendlen = len;

    return pHelperUnit->send();
}

void CloseConn(int fd)
{
    if( g_pFdInfoMap->find(fd) == g_pFdInfoMap->end() )
    {
        return;
    }

    FdInfo &fdInfo = (*g_pFdInfoMap)[fd];
    CHelperUnit* pHelperUnit = fdInfo.pHelperUnit;
    if( pHelperUnit == NULL )
    {
        return ;
    }

    CDecoderUnit *d = pHelperUnit->GetOwner();
	if(g_pDecodeUnitSet->find(d) != g_pDecodeUnitSet->end()){
      log_warning("Warning: decode_unit:%p double deleted,fd:%d",d, fd )   ;
	}
	g_pDecodeUnitSet->insert(d);
    //DELETE( d );
}

void SetVersion(const char *version)
{
    *g_pVersion = (std::string)version;
}

__END_DECLS
